package com.dailyblue.java;

import lombok.SneakyThrows;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

// 字节输入
public class DemoC {
    private static File src = new File("/Users/dailyblue/a/a.txt");

    @SneakyThrows
    private static void a1() {
        byte[] src = "Hello,world!".getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(src);
        int by = bais.read(); // by是读取的内容
        System.out.println(by);
        System.out.println((char) (by));
        bais.close();
    }

    @SneakyThrows
    private static void a2() {
        byte[] src = "Hello,world!".getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(src);
        byte[] bytes = new byte[10];
        int len = bais.read(bytes); // len：实际读取的长度
        String str = new String(bytes, 0, len);
        System.out.println(str);
        bais.close();
    }

    @SneakyThrows
    private static void a3() {
        byte[] src = "Hello,world!".getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(src);
        int by;
        do {
            by = bais.read();
            System.out.print((char) by);
        } while (by != -1);
        bais.close();
    }

    @SneakyThrows
    private static void b1() {
        InputStream in = new FileInputStream(src);
        int by = in.read();
        if (by != -1) {
            System.out.println((char) by);
        }
        in.close();
    }

    @SneakyThrows
    private static void b2() {
        InputStream in = new FileInputStream(src);
        byte[] bytes = new byte[3];
        int len = in.read(bytes);
        String str = new String(bytes, 0, len);
        System.out.println(str);
        in.close();
    }

    @SneakyThrows
    private static void b3() {
        InputStream in = new FileInputStream(src);
        byte[] bytes = new byte[3];
        while (true) {
            int len = in.read(bytes);
            if (len == -1) {
                in.close();
                return;
            }
            String str = new String(bytes, 0, len);
            System.out.print(str);
        }

    }

    public static void main(String[] args) {
        b3();
    }
}
